using System.Diagnostics;
using System.Windows;

using GrpcClient.Models;

using GRPCDemo.Protocol;

namespace GrpcClient.Utility
{
    public class CommonUtility
    {
        public static event Action<string>? NotifyMessageEvent;

        public static Task Wait(ResponseCache condition)
        {
            return Task.Run(() =>
            {
                int outTime = 0;

                Stopwatch sw = new Stopwatch();
                sw.Start();

                while (!condition.HasResponse && outTime++ < 10000)
                {
                    Sleep(1);
                }

                if (!string.IsNullOrEmpty(condition.ErrMsg))
                {
                    if (NotifyMessageEvent != null)
                        NotifyMessageEvent.Invoke(condition.ErrMsg);
                }

                sw.Stop();
                Debug.WriteLine("用时：" + sw.ElapsedMilliseconds);
            });
        }


        public static void Sleep(int ms)
        {
            var sw = Stopwatch.StartNew();
            var sleepMs = ms - 16;
            if (sleepMs > 0)
            {
                Thread.Sleep(sleepMs);
            }
            while (sw.ElapsedMilliseconds < ms)
            {
                Thread.Sleep(0);
            }
        }

    }
}
